const config = require('../config/config');
import * as request from 'request'
let deploy = process.env.NODE_ENV == 'production' ? config.production : config.development;
import * as crypto from "crypto"
const sign = getSign()

function getSign () {
    return crypto.createHash('md5').update(deploy.key + deploy.parkNumber).digest('hex')
}

async function postToBlueCard (url: string, data: any) :Promise<any> {
    return new Promise((resolve, reject) => {
        request.post(url, {headers: {'Content-Type': 'application/json', sign}, body: JSON.stringify(data)}, function (err, res, body) {
            if (err) {
                console.error("blueCard fild:", err)
                throw err
            }
            const ret = JSON.parse(body)
            console.log('blueCard res:', ret)
            resolve(ret)
        })
    })
}

/**
 * 获取账单(注：账单时间)
 * @param {string} plate 车牌（如"京 A12345）
 * @param {string} couponTime 优惠时长（单位小时，如1.5）
 */
async function getBill(plate: string, couponTime: string) :Promise<IChargeRes>{
    const url = `${deploy.blueCardApi}/getChargebf`
    let data: ICharge
    data.parkNumber = deploy.parkNumber
    data.orderId = ''           // 可不填
    data.plate = plate
    data.couponTime = couponTime
    const res: IChargeRes = await postToBlueCard(url, data)
    return res
}

/**
 * 通知蓝卡 订单已支付
 * @param {string} plate 车牌
 * @param {number} payCharge 应收金额，两位小数
 * @param {number} realCharge 实收金额，两位小数
 * @param {string} payTime 支付时间 yyyy-MM-dd HH:mm:ss
 * @param {string} payType 支付类型 支付宝 微信 云优惠
 * @param {string} getTimes 结算时间 yyyy-MM-dd HH:mm:ss
 * @param {string} transactionID 交易流水号
 * @param {string} outTradeNo 支付流水号(算费返回)
 */
async function postPay(plate: string, payCharge: number, realCharge: number, payTime: string,
    payType: string, getTimes: string, transactionID: string, outTradeNo: string) :Promise<IPayRes> {
    const url = `${deploy.blueCardApi}/sendPayRes`
    let data: IPay
    data.parkNumber = deploy.parkNumber
    data.orderId = ''           // 可不填
    data.plate = plate
    data.payCharge = String(payCharge)
    data.realCharge = String(realCharge)
    data.payTime = payTime
    data.payType = payType
    data.payChannel = '自助缴费'
    data.getTimes = getTimes
    data.transactionID = transactionID
    data.outTradeNo = outTradeNo
    const res: IPayRes = await postToBlueCard(url, data)
    return res
}
